﻿namespace X2OPC.Core.Common
{
    using System;
    using System.Runtime.InteropServices;

    public class EnumString: System.Runtime.InteropServices.ComTypes.IEnumString
    {
        private string[] _sources;
        private int current;
        private int size;
        public EnumString(string[] sources)
        {
            if (sources != null) _sources = sources;
            this.current = 0;
            this.size = (sources == null) ? 0 : _sources.Length;
        }

        #region IEnumString 成员

        public void Clone(out System.Runtime.InteropServices.ComTypes.IEnumString ppenum)
        {
            ppenum = new EnumString(this._sources);
        }

        public int Next(int celt, string[] rgelt, IntPtr pceltFetched)
        {
            if (celt < 0)
            {
                return -2147024809;
            }

            int index = 0;

            while ((this.current < this.size) && (celt > 0))
            {
                object item = this._sources[this.current];
                bool useDisplayMember = false;
                 
                if (!useDisplayMember)
                {
                    if (item != null)
                        rgelt[index] = item.ToString();
                }
                current++;
                index++;
                celt--;
            }

            if (pceltFetched != IntPtr.Zero)
            {
                Marshal.WriteInt32(pceltFetched, index);
            }
            if (celt != 0)
            {
                return 1;
            }

            return 0;
        }

        public void Reset()
        {
            this.current = 0;
        }

        public int Skip(int celt)
        {
            this.current += celt;
            if (this.current >= this.size)
            {
                return 1;
            }
            return 0;
        }

        #endregion
    }
}
